package com.coursebooking.controller;

import com.coursebooking.model.User;
import com.coursebooking.service.UserService;
import com.coursebooking.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserService userService;

    @Autowired
    JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
        try {
            // 验证输入参数
            if (loginRequest.getUsername() == null || loginRequest.getUsername().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户名不能为空"));
            }
            if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("密码不能为空"));
            }
            
            User user = userService.findByUsername(loginRequest.getUsername());
            if (user == null) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户名或密码错误"));
            }


            // 验证密码
            if (!userService.validatePassword(loginRequest.getPassword(), user.getPassword())) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户名或密码错误"));
            }
            
            // 检查用户是否激活
            if (!user.getIsActive()) {
                return ResponseEntity.badRequest().body(new MessageResponse("账户已被禁用"));
            }
            
            String jwt = jwtUtil.generateToken(user.getUsername(), user.getRole().name());
            
            // 更新最后登录时间
            userService.updateLastLogin(user.getUsername());

            return ResponseEntity.ok(new JwtResponse(jwt, user.getId(), user.getUsername(), 
                    user.getEmail(), user.getRole().name(), user.getRelatedId()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("登录失败，请稍后重试"));
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody SignupRequest signUpRequest) {
        try {
            // 验证输入参数
            if (signUpRequest.getUsername() == null || signUpRequest.getUsername().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户名不能为空"));
            }
            if (signUpRequest.getPassword() == null || signUpRequest.getPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("密码不能为空"));
            }
            if (signUpRequest.getEmail() == null || signUpRequest.getEmail().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("邮箱不能为空"));
            }
            if (signUpRequest.getRole() == null || signUpRequest.getRole().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("角色不能为空"));
            }
            
            // 验证用户名长度
            if (signUpRequest.getUsername().length() < 3 || signUpRequest.getUsername().length() > 20) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户名长度必须在3-20个字符之间"));
            }
            
            // 验证密码长度
            if (signUpRequest.getPassword().length() < 6) {
                return ResponseEntity.badRequest().body(new MessageResponse("密码长度不能少于6个字符"));
            }
            
            // 验证邮箱格式
            if (!signUpRequest.getEmail().matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
                return ResponseEntity.badRequest().body(new MessageResponse("邮箱格式不正确"));
            }

            if (userService.existsByUsername(signUpRequest.getUsername())) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户名已存在"));
            }

            if (userService.existsByEmail(signUpRequest.getEmail())) {
                return ResponseEntity.badRequest().body(new MessageResponse("邮箱已存在"));
            }

            User.Role role;
            try {
                role = User.Role.valueOf(signUpRequest.getRole().toUpperCase());
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().body(new MessageResponse("无效的角色类型"));
            }

            User user = userService.createUser(
                    signUpRequest.getUsername().trim(),
                    signUpRequest.getPassword(),
                    signUpRequest.getEmail().trim().toLowerCase(),
                    role,
                    signUpRequest.getRelatedId()
            );

            return ResponseEntity.ok(new MessageResponse("用户注册成功"));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new MessageResponse(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("注册失败，请稍后重试"));
        }
    }

 @PostMapping("/updatePassword")
    public ResponseEntity<?> updatePassword(@RequestBody PasswordRequest passwordRequest) {
        try {
            // 验证输入参数
            if (passwordRequest.getId() == null) {
                return ResponseEntity.badRequest().body(new MessageResponse("用户id不能为空"));
            }
            if (passwordRequest.getNewPassword() == null || passwordRequest.getNewPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("密码不能为空"));
            }
            if (passwordRequest.getOldPassword() == null || passwordRequest.getOldPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(new MessageResponse("旧密码不能为空"));
            }
            // 验证密码长度
            if (passwordRequest.getNewPassword().length() < 6) {
                return ResponseEntity.badRequest().body(new MessageResponse("密码长度不能少于6个字符"));
            }
            userService.changePassword(passwordRequest.getId(), passwordRequest.getNewPassword(), passwordRequest.getOldPassword());

            return ResponseEntity.ok(new MessageResponse("用户注册成功"));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new MessageResponse(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("注册失败，请稍后重试"));
        }
    }

    // 内部类定义
    public static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    // 内部类定义
    public static class PasswordRequest {
        private String newPassword;
        private Long id;
        private String oldPassword;


        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getOldPassword() {
            return oldPassword;
        }

        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }

    }

    public static class SignupRequest {
        private String username;
        private String email;
        private String password;
        private String role;
        private Long relatedId;

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public String getRole() { return role; }
        public void setRole(String role) { this.role = role; }
        public Long getRelatedId() { return relatedId; }
        public void setRelatedId(Long relatedId) { this.relatedId = relatedId; }
    }

    public static class JwtResponse {
        private String token;
        private String type = "Bearer";
        private Long id;
        private String username;
        private String email;
        private String role;
        private Long relatedId;

        public JwtResponse(String accessToken, Long id, String username, String email, String role, Long relatedId) {
            this.token = accessToken;
            this.id = id;
            this.username = username;
            this.email = email;
            this.role = role;
            this.relatedId = relatedId;
        }

        // Getters
        public String getToken() { return token; }
        public String getType() { return type; }
        public Long getId() { return id; }
        public String getUsername() { return username; }
        public String getEmail() { return email; }
        public String getRole() { return role; }
        public Long getRelatedId() { return relatedId; }
    }

    public static class MessageResponse {
        private String message;

        public MessageResponse(String message) {
            this.message = message;
        }

        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }
}